<?php
/**
 * 账号权限相关
 * User: minyifei
 * Date: 15/7/8
 * Time: 下午4:37
 */
use MyfApi\Model\User,
    MyfApi\Model\UserToken;
use MyfApi\Libs\ErrorCode;

class AuthController extends \MyfApi\Libs\BaseController{

    /**
     * 读取匿名token
     */
    public function anonymous(){
        $token = $this->createToken(0);
        $data = array(
            "token"=>$token,
        );
        $this->echoSuccess($data);
    }

    /**
     * 登陆接口
     */
    public function login(){
        $mobile = post("mobile");
        $password = post("password");
        if(checkMobile($mobile) && strlen($password)>4){
            $m = new User();
            $user = $m->findFirst(array(
                "mobile=:mobile and password=:password",
                "columns"=>"id,number,mobile,create_time",
                "bind"=>array(
                    "mobile"=>$mobile,
                    "password"=>encodePassword($password),
                ),
            ));
            if($user){
                $user["token"]=UserToken::getToken($user["id"]);
                $user["name"]="闵益飞博客";
                unset($user["id"]);
                $this->echoSuccess($user);
            }else{
                ErrorCode::throwException("用户名或密码错误");
            }
        }else{
            ErrorCode::throwExceptionCode(ErrorCode::PARAM_ERROR);
        }
    }

    /**
     * 创建账号
     */
    public function create(){
        $mobile = post("mobile");
        $password = post("password");
        if(checkMobile($mobile) && strlen($password)>4){
            $m = new User();
            $count = $m->count(array(
                "mobile=:mobile",
                "bind"=>array("mobile"=>$mobile)
            ));
            if($count>0){
                ErrorCode::throwException("手机号已经注册");
            }else{
                $user = User::create($mobile,$password);
                $this->echoSuccess($user);
            }
        }else{
            ErrorCode::throwExceptionCode(ErrorCode::PARAM_ERROR);
        }
    }
}